Popular Searches
Popular Course Categories
Popular Courses

Classes and Objects in Dart

Classes and Objects in Dart

5 mins Object-Oriented Programming in Dart

Classes and Objects in Dart

Classes and objects are fundamental concepts of Object-Oriented Programming (OOP) in Dart. They allow developers to organize data and behavior together, create reusable code, and model real-world entities inside applications.

In the JustAcademy Flutter curriculum, Dart programming includes Object-Oriented Programming, classes, objects, and constructors as core topics. These concepts are important for building structured Flutter applications because Flutter development uses Dart extensively. :contentReference[oaicite:0]{index=0}

1. What is a Class in Dart?

A class is a blueprint or template used to create objects. A class defines the properties (data) and methods (behavior) that its objects can have.

For example, if we want to represent a student in a program, we can create a Student class containing properties such as name, age, and course, along with methods such as displayDetails().

Basic Syntax of a Class

class ClassName {
  // Properties

  // Methods
}

Example

class Student {
  String name = "Rahul";
  int age = 20;

  void displayDetails() {
    print("Name: $name");
    print("Age: $age");
  }
}

In this example, Student is a class. It contains two properties, name and age, and one method called displayDetails().

2. What is an Object?

An object is an instance of a class. When a class is created, it only defines the structure. An object is created from that class so that the properties and methods can actually be used.

A simple way to understand this is:

  • Class: Blueprint or design.
  • Object: Actual instance created from the blueprint.

Creating an Object

class Student {
  String name = "Rahul";
  int age = 20;

  void displayDetails() {
    print(name);
    print(age);
  }
}

void main() {
  Student student1 = Student();

  student1.displayDetails();
}

Here, Student is the class and student1 is an object of the Student class.

3. Class vs Object

Class Object
A blueprint or template An instance of a class
Defines properties and methods Uses those properties and methods
Does not represent a specific instance Represents a specific instance
Example: Student Example: student1

4. Properties in a Class

Properties, also called fields or instance variables, represent the data associated with an object.

class Employee {
  String name = "Amit";
  int age = 25;
  double salary = 45000;
}

In this example:

  • name stores the employee's name.
  • age stores the employee's age.
  • salary stores the employee's salary.

5. Accessing Object Properties

The dot (.) operator is used to access properties and methods of an object.

class Employee {
  String name = "Amit";
  int age = 25;
}

void main() {
  Employee employee = Employee();

  print(employee.name);
  print(employee.age);
}

Output:

Amit
25

6. Changing Object Properties

If a property is not declared as final, its value can normally be changed through the object.

class Student {
  String name = "Rahul";
  int age = 20;
}

void main() {
  Student student = Student();

  student.name = "Aman";
  student.age = 22;

  print(student.name);
  print(student.age);
}

Output:

Aman
22

7. Methods in a Class

A method is a function defined inside a class. Methods describe the behavior or actions that an object can perform.

class Calculator {
  int add(int a, int b) {
    return a + b;
  }

  int multiply(int a, int b) {
    return a * b;
  }
}

void main() {
  Calculator calculator = Calculator();

  print(calculator.add(10, 20));
  print(calculator.multiply(5, 4));
}

Output:

30
20

8. Multiple Objects from One Class

One of the major advantages of classes is that we can create multiple objects from the same class.

class Student {
  String name;
  int age;

  Student(this.name, this.age);

  void display() {
    print("Name: $name");
    print("Age: $age");
  }
}

void main() {
  Student student1 = Student("Rahul", 20);
  Student student2 = Student("Priya", 22);

  student1.display();
  student2.display();
}

Both objects use the same class structure, but each object contains its own data.

9. Constructors in Dart

A constructor is a special function used when creating an object. Constructors are commonly used to initialize the properties of an object.

Constructor Example

class Student {
  String name;
  int age;

  Student(this.name, this.age);
}

void main() {
  Student student = Student("Rahul", 21);

  print(student.name);
  print(student.age);
}

The constructor Student(this.name, this.age) receives values and assigns them to the object's properties.

10. The this Keyword

The this keyword refers to the current object.

class Employee {
  String name;
  double salary;

  Employee(this.name, this.salary);

  void display() {
    print("Employee: $name");
    print("Salary: $salary");
  }
}

Here, this.name and this.salary refer to the properties of the current object.

11. Named Constructors

Dart allows classes to have named constructors. Named constructors can be useful when a class needs multiple ways of creating objects.

class User {
  String name;
  int age;

  User(this.name, this.age);

  User.guest()
      : name = "Guest",
        age = 0;
}

void main() {
  User user1 = User("Rahul", 25);
  User user2 = User.guest();

  print(user1.name);
  print(user2.name);
}

12. Default Values in Classes

Properties can have default values when appropriate.

class Product {
  String name = "Unknown Product";
  double price = 0.0;
  bool available = true;
}

void main() {
  Product product = Product();

  print(product.name);
  print(product.price);
  print(product.available);
}

13. Using final Properties

A property declared with final can be assigned only once.

class User {
  final String id;
  String name;

  User(this.id, this.name);
}

void main() {
  User user = User("U101", "Rahul");

  print(user.id);
  print(user.name);

  user.name = "Aman";

  print(user.name);
}

In this example, name can be changed, while id cannot be reassigned after initialization.

14. Encapsulation with Classes

Classes can be used to organize and control access to data. In Dart, identifiers beginning with an underscore are private to the library.

class BankAccount {
  double _balance = 0;

  void deposit(double amount) {
    if (amount > 0) {
      _balance += amount;
    }
  }

  double getBalance() {
    return _balance;
  }
}

void main() {
  BankAccount account = BankAccount();

  account.deposit(5000);

  print(account.getBalance());
}

Here, _balance is kept behind the class interface and is modified through the deposit() method.

15. Getters and Setters

Getters and setters provide controlled ways to read and update properties.

class Student {
  String _name = "Rahul";

  String get name {
    return _name;
  }

  set name(String value) {
    _name = value;
  }
}

void main() {
  Student student = Student();

  print(student.name);

  student.name = "Aman";

  print(student.name);
}

16. Object Identity

Two objects created from the same class are separate objects. Changing one object's properties does not automatically change the other object's properties.

class Student {
  String name;

  Student(this.name);
}

void main() {
  Student student1 = Student("Rahul");
  Student student2 = Student("Priya");

  student1.name = "Aman";

  print(student1.name);
  print(student2.name);
}

Output:

Aman
Priya

17. Real-World Example: Product Class

Classes are useful for representing real-world entities such as products in an e-commerce application.

class Product {
  String name;
  double price;
  int quantity;

  Product(this.name, this.price, this.quantity);

  double totalPrice() {
    return price * quantity;
  }

  void displayProduct() {
    print("Product: $name");
    print("Price: ₹$price");
    print("Quantity: $quantity");
    print("Total: ₹${totalPrice()}");
  }
}

void main() {
  Product product = Product("Laptop", 50000, 2);

  product.displayProduct();
}

This example demonstrates how a class can combine data and behavior in one structure.

18. Real-World Example: Bank Account

class BankAccount {
  String accountHolder;
  double balance;

  BankAccount(this.accountHolder, this.balance);

  void deposit(double amount) {
    balance += amount;
  }

  void withdraw(double amount) {
    if (amount <= balance) {
      balance -= amount;
    } else {
      print("Insufficient balance");
    }
  }

  void displayBalance() {
    print("Account Holder: $accountHolder");
    print("Balance: ₹$balance");
  }
}

void main() {
  BankAccount account = BankAccount("Rahul", 10000);

  account.deposit(5000);
  account.withdraw(2000);

  account.displayBalance();
}

19. Classes and Objects in Flutter

Classes and objects are heavily used in Flutter development. The JustAcademy Flutter curriculum places classes and objects within Dart's Object-Oriented Programming fundamentals, alongside constructors, inheritance, polymorphism, and abstraction. :contentReference[oaicite:1]{index=1}

Flutter itself uses classes extensively. Widgets, screens, models, services, controllers, and other application components can be represented using classes.

Simple Flutter Widget Example

import 'package:flutter/material.dart';

class HomeScreen extends StatelessWidget {
  const HomeScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Home"),
      ),
      body: const Center(
        child: Text("Welcome to Flutter"),
      ),
    );
  }
}

In this example, HomeScreen is a class. It extends StatelessWidget and provides a build() method that describes the widget's UI.

20. Model Classes in Flutter

Classes are commonly used to represent data received from APIs, databases, or local storage. Such classes are often called model classes.

class User {
  final int id;
  final String name;
  final String email;

  User({
    required this.id,
    required this.name,
    required this.email,
  });
}

void main() {
  User user = User(
    id: 101,
    name: "Rahul",
    email: "[email protected]",
  );

  print(user.name);
  print(user.email);
}

21. Creating Multiple Model Objects

class Product {
  final String name;
  final double price;

  Product({
    required this.name,
    required this.price,
  });
}

void main() {
  List products = [
    Product(name: "Laptop", price: 50000),
    Product(name: "Mobile", price: 25000),
    Product(name: "Headphones", price: 3000),
  ];

  for (Product product in products) {
    print("${product.name}: ₹${product.price}");
  }
}

This pattern is particularly useful when displaying lists of products or other records in Flutter applications.

22. Class with a Method Returning an Object

class Address {
  String city;
  String country;

  Address(this.city, this.country);
}

class User {
  String name;
  Address address;

  User(this.name, this.address);

  void display() {
    print("Name: $name");
    print("City: ${address.city}");
    print("Country: ${address.country}");
  }
}

void main() {
  Address address = Address("Mumbai", "India");

  User user = User("Rahul", address);

  user.display();
}

23. Composition: Objects Inside Other Objects

A class can contain another class as one of its properties. This is a common way to model relationships between objects.

class Engine {
  void start() {
    print("Engine started");
  }
}

class Car {
  Engine engine = Engine();

  void startCar() {
    engine.start();
    print("Car started");
  }
}

void main() {
  Car car = Car();

  car.startCar();
}

24. Static Members in a Class

A static member belongs to the class itself rather than to a particular object.

class Counter {
  static int count = 0;

  Counter() {
    count++;
  }
}

void main() {
  Counter();
  Counter();
  Counter();

  print(Counter.count);
}

Output:

3

25. Class and Object Example: Student Management

class Student {
  String name;
  int rollNumber;
  double marks;

  Student(this.name, this.rollNumber, this.marks);

  String getResult() {
    if (marks >= 40) {
      return "Pass";
    }

    return "Fail";
  }

  void displayDetails() {
    print("Name: $name");
    print("Roll Number: $rollNumber");
    print("Marks: $marks");
    print("Result: ${getResult()}");
  }
}

void main() {
  Student student1 = Student("Rahul", 101, 85);
  Student student2 = Student("Priya", 102, 72);

  student1.displayDetails();
  print("");

  student2.displayDetails();
}

26. Class and Object Example: Employee Management

class Employee {
  String name;
  String department;
  double salary;

  Employee(this.name, this.department, this.salary);

  void display() {
    print("Name: $name");
    print("Department: $department");
    print("Salary: ₹$salary");
  }
}

void main() {
  Employee employee1 =
      Employee("Amit", "Development", 60000);

  Employee employee2 =
      Employee("Priya", "Testing", 55000);

  employee1.display();

  print("");

  employee2.display();
}

27. Advantages of Classes and Objects

  • Code organization: Related data and behavior can be grouped together.
  • Reusability: One class can be used to create many objects.
  • Maintainability: Application logic can be divided into manageable classes.
  • Encapsulation: Data and operations can be controlled through class interfaces.
  • Scalability: Classes help structure larger applications.
  • Real-world modeling: Real entities can be represented as objects.
  • Flutter integration: Classes are used throughout Flutter applications.

28. Common Mistakes While Using Classes and Objects

Mistake 1: Forgetting to Create an Object

Defining a class does not automatically create an object.

class Student {
  String name = "Rahul";
}

void main() {
  Student student = Student();

  print(student.name);
}

Mistake 2: Incorrect Constructor Arguments

class Student {
  String name;
  int age;

  Student(this.name, this.age);
}

void main() {
  Student student = Student("Rahul", 20);
}

The object creation should provide the values required by the constructor.

Mistake 3: Trying to Modify a final Property

class User {
  final String id;

  User(this.id);
}

Once id has been initialized, it cannot be reassigned.

29. Best Practices for Classes in Dart

  • Use meaningful class names such as Student, Product, or User.
  • Use PascalCase for class names.
  • Keep a class focused on a clear responsibility.
  • Use constructors to initialize required data.
  • Use final for values that should not be reassigned.
  • Use named parameters when they make object creation easier to understand.
  • Keep internal implementation details controlled where appropriate.
  • Create model classes for structured application data.
  • Use methods to keep related behavior with the data it operates on.

30. Class and Object Flow

Class
  ↓
Define properties and methods
  ↓
Create object
  ↓
Initialize object
  ↓
Access properties
  ↓
Call methods
  ↓
Perform application operations

31. Quick Revision

Concept Meaning Example
Class Blueprint for creating objects class Student {}
Object Instance of a class Student s = Student();
Property Data stored by an object String name;
Method Behavior defined inside a class void display() {}
Constructor Used during object creation Student(this.name);
this Refers to the current object this.name
Getter Reads a computed or controlled property get name
Setter Updates a property through controlled logic set name()
Static Member associated with the class static int count;

32. Practice Exercises

  1. Create a Book class with title, author, and price properties.
  2. Create three objects from the Book class.
  3. Create a Car class with brand, model, and price.
  4. Add a method to the Car class that displays its details.
  5. Create a BankAccount class with deposit and withdrawal methods.
  6. Create a Product model class suitable for a Flutter e-commerce application.
  7. Create a User class using named parameters and a constructor.
  8. Create a Flutter widget class that displays information from a Dart model object.

33. Key Takeaways

  • A class is a blueprint used to define data and behavior.
  • An object is an instance of a class.
  • Properties store object data.
  • Methods define object behavior.
  • Constructors initialize objects.
  • The this keyword refers to the current object.
  • Multiple objects can be created from the same class.
  • Classes are widely used in Flutter for widgets, models, services, and application logic.
  • Understanding classes and objects provides an important foundation for learning inheritance, polymorphism, abstraction, and other OOP concepts.

34. Learn Flutter with JustAcademy

JustAcademy's Flutter training includes Dart fundamentals and Object-Oriented Programming, including classes, objects, and constructors, as part of its curriculum. The course also progresses into Flutter widgets, UI development, APIs, Firebase, state management, projects, and other application-development topics. :contentReference[oaicite:2]{index=2}

Visit JustAcademy Flutter Training

Register for JustAcademy Course Demo

whatsapp